import requests
import os
from urllib.parse import urlparse
from datetime import datetime

# from applications.functions.view_html_text import view_html_text

def view_html_text(url: str) -> str:
    """
    极简版网页保存工具：只需传入URL，自动保存到当前文件夹
    
    参数:
        url: 目标网页URL
        
    返回:
        str: 成功返回保存的文件路径，失败返回空字符串
    """
    try:
        # 生成基于域名和时间戳的文件名
        domain = urlparse(url).netloc.replace('www.', '').split('.')[0]
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{domain}_{timestamp}.html"
        
        # 获取网页内容
        response = requests.get(
            url, 
            headers={'User-Agent': 'Mozilla/5.0'},
            timeout=10
        )
        response.raise_for_status()
        
        # 保存到当前目录
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(response.text)
        
        return os.path.abspath(filename)
    
    except Exception as e:
        print(f"❌ 保存失败: {str(e)}")
        return ""